﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using bdnt_pets_system.Tools;
using bdnt_pets_system.SystemServiceReference;
using System.Windows.Data;
using bdnt_pets_system_Entity;
using bdnt_pets_system.Resources;
using System.Collections.ObjectModel;

namespace bdnt_pets_system.PageViews.SystemViews
{
    public partial class NewUserControl : BaseUserControl
    {
        SystemServiceReference.SystemServiceClient sysClient;

        public NewUserControl(Int32 objId = 0)
        {
            InitializeComponent();
            BingData();
            sysClient = new SystemServiceReference.SystemServiceClient();
            InitEvnet();
            sysClient.GetRoleObjListConditionAsync("");
            if (objId == 0)
            {
                CuTbl_Employee = new Tbl_Employee();
                rbCy.IsChecked = true;
                sysClient.GetRoleObjListConditionAsync("");
            }
            else
                sysClient.GetEmployeeObjByIdAsync(objId);
        }

        public Tbl_Employee CuTbl_Employee
        {
            get
            {
                var cuo = (this.DataContext as Tbl_Employee);
                return cuo == null ? new Tbl_Employee() : cuo;
            }
            set { this.DataContext = value; }
        }

        void InitEvnet()
        {
            sysClient.GetRoleObjListConditionCompleted += new EventHandler<GetRoleObjListConditionCompletedEventArgs>(sysClient_GetRoleObjListConditionCompleted);
            sysClient.GetEmployeeObjByIdCompleted += new EventHandler<GetEmployeeObjByIdCompletedEventArgs>(sysClient_GetEmployeeObjByIdCompleted);
            sysClient.SaveEmployeeRoleObjCompleted += new EventHandler<SaveEmployeeRoleObjCompletedEventArgs>(sysClient_SaveEmployeeRoleObjCompleted);
            sysClient.GetDictListByPidCompleted += new EventHandler<GetDictListByPidCompletedEventArgs>(sysClient_GetDictListByPidCompleted);

            btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
            btnOk.Click += new RoutedEventHandler(btnOk_Click);
            cbShop.SelectionChanged += new SelectionChangedEventHandler(cbShop_SelectionChanged);
        }

        void cbShop_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbShop.SelectedValue == null)
                return;
            if (AllStaionList == null)
                return;
            var cuStations = AllStaionList.Where(p => p.ShopId.ToString() == cbShop.SelectedValue.ToString()).ToList();
            cbStation.ItemsSource = cuStations;
            cbStation.SelectedValuePath = "Id";
            cbStation.DisplayMemberPath = SessionManager.IsCN_ZH ? "StationName" : "en_StationName";
            if (CuTbl_Employee.StationId != 0)
            {
                var cus = cuStations.FirstOrDefault(p => p.Id == CuTbl_Employee.StationId);
                cbStation.SelectedIndex = cus == null ? -1 : cuStations.IndexOf(cus);
            }
        }

        void sysClient_GetDictListByPidCompleted(object sender, GetDictListByPidCompletedEventArgs e)
        {
            cbDept.ItemsSource = e.Result.OrderBy(p => p.Sequence);
            cbDept.DisplayMemberPath = "DictName";
            cbDept.SelectedValuePath = "DictValue";
            if (!string.IsNullOrEmpty(CuTbl_Employee.DeptNo))
            {
                var cuDept = e.Result.FirstOrDefault(p => p.DictValue == CuTbl_Employee.DeptNo);
                cbDept.SelectedIndex = cuDept == null ? -1 : e.Result.IndexOf(cuDept);
            }
        }

        void sysClient_GetEmployeeObjByIdCompleted(object sender, GetEmployeeObjByIdCompletedEventArgs e)
        {
            CuTbl_Employee = e.Result;
            tbRePwd.Password = CuTbl_Employee.LoginPwd;
            if (CuTbl_Employee.IsShopManager)
                rbFzr.IsChecked = true;
            else rbCy.IsChecked = true;
            sysClient.GetRoleObjListConditionAsync("");
        }

        void sysClient_GetRoleObjListConditionCompleted(object sender, GetRoleObjListConditionCompletedEventArgs e)
        {
            var re = e.Result;
            spRoles.Children.Clear();
            if (re != null)
            {
                List<int> ls = !string.IsNullOrEmpty(CuTbl_Employee.RoleIds) ? CuTbl_Employee.RoleIds.Split(',').Where(p => !string.IsNullOrEmpty(p)).Select(p => Int32.Parse(p)).ToList() : new List<int>();
                foreach (var item in re)
                {
                    CheckBox ck = new CheckBox()
                    {
                        VerticalAlignment = System.Windows.VerticalAlignment.Center,
                        Margin = new Thickness(0, 0, 5, 0),
                        Content = item.RoleName
                    };
                    if (ls.Contains(item.Id))
                    {
                        ck.IsChecked = true;
                    }
                    ck.Tag = item;
                    spRoles.Children.Add(ck);
                }
            }
            //查询数据
            DataServiceReference.DataServiceClient dataClient = new DataServiceReference.DataServiceClient();
            dataClient.GetAllStationListCompleted += new EventHandler<DataServiceReference.GetAllStationListCompletedEventArgs>(dataClient_GetAllStationListCompleted);
            dataClient.GetAllStationListAsync();
            dataClient.CloseAsync();
        }
        ObservableCollection<Tbl_Station> AllStaionList;
        void dataClient_GetAllStationListCompleted(object sender, DataServiceReference.GetAllStationListCompletedEventArgs e)
        {
            AllStaionList = e.Result;
            gdStations.Children.Clear();
            if (AllStaionList != null)
            {
                List<int> ls = !string.IsNullOrEmpty(CuTbl_Employee.StationIds) ? CuTbl_Employee.StationIds.Split(',').Where(p => !string.IsNullOrEmpty(p)).Select(p => Int32.Parse(p)).ToList() : new List<int>();
                int rowIndex = 0;
                var shops = AllStaionList.Select(p => p.ShopId).Distinct();
                foreach (var item in shops)
                {
                    var sN = AllStaionList.FirstOrDefault(p => p.ShopId == item).ShopName;
                    gdStations.RowDefinitions.Add(new RowDefinition());
                    CheckBox ck = new CheckBox()
                    {
                        Margin = new Thickness(0, 0, 5, 10),
                        Content = sN
                    };
                    ck.Checked += new RoutedEventHandler(ck_Checked);
                    ck.Unchecked += new RoutedEventHandler(ck_Checked);
                    Grid.SetRow(ck, rowIndex);
                    Grid.SetColumn(ck, 0);
                    gdStations.Children.Add(ck);

                    WrapPanel wp = new WrapPanel() { Margin = new Thickness(0, 0, 0, 10) };
                    Grid.SetRow(wp, rowIndex);
                    Grid.SetColumn(wp, 1);
                    ck.Tag = wp;

                    bool isVisble = false;
                    var stations = AllStaionList.Where(p => p.ShopId == item).ToList();
                    stations.Where(p => !string.IsNullOrEmpty(p.StationName)).ToList().ForEach(p =>
                    {
                        CheckBox ck1 = new CheckBox()
                        {
                            Margin = new Thickness(0, 0, 5, 0),
                            Content = p.StationName,
                            Tag = p.Id
                        };
                        if (ls.Contains(p.Id))
                        {
                            ck.IsChecked = ck1.IsChecked = true;
                            isVisble = true;
                        }
                        wp.Children.Add(ck1);
                    });

                    gdStations.Children.Add(wp);
                    wp.Visibility = isVisble == true ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    rowIndex++;
                }
            }

            var gws = HelpTools.DistinctList(AllStaionList.Select(p => new SimpleObject<int, string>() { Item1 = p.ShopId, Item2 = SessionManager.IsCN_ZH ? p.ShopName : p.en_ShopName }).ToList());
            cbShop.ItemsSource = gws;
            cbShop.DisplayMemberPath = "Item2";
            cbShop.SelectedValuePath = "Item1";

            var cushop = gws.FirstOrDefault(p => p.Item1 == CuTbl_Employee.ShopId);
            cbShop.SelectedIndex = cushop == null ? -1 : gws.IndexOf(cushop);

            sysClient.GetDictListByPidAsync(5);
        }

        void ck_Checked(object sender, RoutedEventArgs e)
        {
            var cuObj = (sender as CheckBox);
            var cuWp = cuObj.Tag as WrapPanel;
            if (cuObj.IsChecked == true)
                cuWp.Visibility = System.Windows.Visibility.Visible;
            else
            {
                cuWp.Visibility = System.Windows.Visibility.Collapsed;
                foreach (var item in cuWp.Children)
                {
                    (item as CheckBox).IsChecked = false;
                }
            }
        }

        void sysClient_SaveEmployeeRoleObjCompleted(object sender, SaveEmployeeRoleObjCompletedEventArgs e)
        {
            if (e.Result)
            {
                App.ToPage(new UserManagerControl());
            }
            else
            {
                errorMsg.Text = MyStrings.bcsb;
            }
        }

        void BingData()
        {
            tbXm.SetBinding(TextBox.TextProperty, new Binding("EmpName")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });
            tbBh.SetBinding(TextBox.TextProperty, new Binding("EmpNo")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });
            tbEmail.SetBinding(TextBox.TextProperty, new Binding("Email")
            {
                Mode = BindingMode.TwoWay
            });
            tbTelephone.SetBinding(TextBox.TextProperty, new Binding("Telephone")
            {
                Mode = BindingMode.TwoWay
            });
            tbLoginName.SetBinding(TextBox.TextProperty, new Binding("LoginName")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });
            tbPwd.SetBinding(PasswordBox.PasswordProperty, new Binding("LoginPwd")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });
        }

        /// <summary>
        /// 字段验证方法
        /// </summary>
        void BindgExpression()
        {
            tbXm.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            tbBh.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            tbLoginName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            tbPwd.GetBindingExpression(PasswordBox.PasswordProperty).UpdateSource();
        }

        void btnOk_Click(object sender, RoutedEventArgs e)
        {
            BindgExpression();
            if (vs.Errors.Count > 0)
            {
                errorMsg.Text = MyStrings.sjtxbq;// "数据填写不全！";
                return;
            }

            if (string.IsNullOrEmpty(tbRePwd.Password))
            {
                errorMsg.Text = MyStrings.qrmmbnwk;// "确认密码不能为空！";
                return;
            }

            if (tbRePwd.Password != CuTbl_Employee.LoginPwd)
            {
                errorMsg.Text = MyStrings.mmsrbyz;// "密码输入不一致！";
                return;
            }

            List<int> roleIds = new List<int>();
            foreach (var item in spRoles.Children)
            {
                var cuk = item as CheckBox;
                if (cuk != null && cuk.IsChecked == true)
                {
                    roleIds.Add((cuk.Tag as Tbl_Role).Id);
                }
            }

            List<int> stationIds = new List<int>();
            foreach (var item in gdStations.Children)
            {
                var cuk = item as CheckBox;
                if (cuk != null)
                {
                    var cuwp = (cuk.Tag as WrapPanel);
                    foreach (var ck in cuwp.Children)
                    {
                        var cuSelectCk = ck as CheckBox;
                        if (cuSelectCk.IsChecked.Value)
                            stationIds.Add(Int32.Parse(cuSelectCk.Tag.ToString()));
                    }
                }
            }

            CuTbl_Employee.IsShopManager = rbFzr.IsChecked.Value;
            CuTbl_Employee.ShopId = cbShop.SelectedValue != null ? Int32.Parse(cbShop.SelectedValue.ToString()) : 0;
            CuTbl_Employee.StationId = cbStation.SelectedValue != null ? Int32.Parse(cbStation.SelectedValue.ToString()) : 0;
            CuTbl_Employee.DeptNo = cbDept.SelectedValue != null ? cbDept.SelectedValue.ToString() : "";
            CuTbl_Employee.CreateTime = CuTbl_Employee.Id == 0 ? DateTime.Now : CuTbl_Employee.CreateTime;
            CuTbl_Employee.RoleIds = string.Join(",", roleIds);
            CuTbl_Employee.StationIds = string.Join(",", stationIds);
            sysClient.SaveEmployeeRoleObjAsync(CuTbl_Employee);
        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            App.ToPage(new UserManagerControl());
        }

    }
}
